package Export;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import DataModel.Feature;
import DataModel.FeatureHolder;
import Viewer.FileChooserX;

/**
 * This class is for the export of a gff3 file.<br>
 * <a
 * href="http://genome.ucsc.edu/FAQ/FAQformat.html#format3">http://genome.ucsc
 * .edu/FAQ/FAQformat.html#format3</a>
 * 
 * @author Stefan Lorenz<br>
 * <br>
 *         26.11.2012
 */
public class ExportBed12 {

	/**
	 * List of {@link Feature}s to export
	 */
	private ArrayList<Feature> list;

	/**
	 * Filechooser
	 */
	private FileChooserX chooserX;

	/**
	 * Contructor of the gff3 exporter
	 * 
	 * @param list
	 *            list with features to export
	 * @param chooserX
	 *            filechooser
	 */
	public ExportBed12(FeatureHolder list, FileChooserX chooserX) {
		this.chooserX = chooserX;
		this.list = list;
		try {
			exportBed();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Exports the gff3
	 * 
	 * @throws IOException
	 */
	private void exportBed() throws IOException {
		if (this.chooserX.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = this.chooserX.getSelectedFile();
			if (!(file.getName().endsWith(".bed") || file.getName().endsWith(".bed12")))
				file = new File(file.getAbsolutePath() + ".bed");

			BufferedWriter writer = new BufferedWriter(new FileWriter(file));

			for (int i = 0; i < this.list.size(); i++) {
				writeBed12(writer, this.list.get(i));
			}
			writer.flush();
			writer.close();
		}
	}

	/**
	 * Writes {@link Feature} in gff3 format
	 * 
	 * @param writer
	 *            writer to write
	 * @param f
	 *            feature to export
	 * @throws IOException
	 */
	private void writeBed12(BufferedWriter writer, Feature f) throws IOException {
		String resLine= "";
		
		resLine = f.getLocus()+"\t"+f.getStart()+"\t"+f.getStop()+"\t"+f.getName()+"\t0"+"\t"+f.getStrand()+"\t"+f.getStart()+"\t"+f.getStop()+"\t"+"255,0,0\t"+f.getListOfPositions().size();
		
		String size = "";
		String start = "";
		for (int i = 0; i < f.getListOfPositions().size(); i++) {
			int relStart = f.getListOfPositions().get(i).getStart()-f.getStart();
			start += relStart+",";
			int exonSize = f.getListOfPositions().get(i).getStop()-f.getListOfPositions().get(i).getStart();
			size += exonSize+",";
		}
		resLine += "\t"+size+"\t"+start;
		writer.write(resLine);
		writer.newLine();
		writer.flush();
	}
}
